package com.yoki.cloud.common.code.db.builder;

import com.yoki.cloud.common.code.db.property.DBColumnProperty;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by SunnyWen on 2017/6/27.
 */
public class DBColumnBuilder {

    private Connection connection;

    public DBColumnBuilder(Connection connection) {
        this.connection = connection;
    }

    public List<DBColumnProperty> buildColumnList(String tableName){
        List<DBColumnProperty> list = new ArrayList<>() ;
        try {
            String currentCatalog = connection.getCatalog();
            ResultSet rs = connection.getMetaData().getColumns(currentCatalog, null, tableName, null);
            while (rs.next()) {
                DBColumnProperty column = new DBColumnProperty();
                column.setTableCat(rs.getString(1));
                column.setTableScheme(rs.getString(2));
                column.setTableName(rs.getString(3));
                column.setColumnName(rs.getString(4));
                column.setDataType(rs.getInt(5));

                column.setTypeName(rs.getString(6));
                column.setColumnSize(rs.getInt(7));
                column.setDecimalDigits(rs.getInt(9));
                column.setNumPrecRadix(rs.getInt(10));


                column.setNullable(rs.getInt(11));
                column.setRemarks(rs.getString(12));
                column.setColumnDef(rs.getString(13));
                column.setColumnDef(rs.getString(13));

                column.setCharOctetLength(rs.getInt(16));
                column.setOrdinalPosition(rs.getInt(17));
                column.setIsNullable(rs.getString(18));
                column.setScopeCatalog(rs.getString(19));
                column.setScopeSchema(rs.getString(20));

                column.setScopeTable(rs.getString(21));
                column.setSourceDataType(rs.getShort(22));
                column.setIsAutoincrement(rs.getString(23));
                column.setIsGeneratedColumn(rs.getString(24));
                list.add(column);
            }
            rs.close();
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }

}
